package com.twotiger.and.activity.current;

import java.util.HashMap;

import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import app.twotiger.p2p.R;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.twotiger.and.Constants;
import com.twotiger.and.activity.base.BaseActivity;
import com.twotiger.and.activity.base.BaseHandler;
import com.twotiger.and.activity.base.SubTitle;
import com.twotiger.and.bean.Basebean;
import com.twotiger.and.bean.CurrentEnter;
import com.twotiger.and.bean.Interest;
import com.twotiger.and.bean.ToProjectXOut;
import com.twotiger.and.util.ArithUtils;
import com.twotiger.and.util.PromptManager;
import com.twotiger.and.util.PromptManager.ReChargeClickListener;
import com.twotiger.and.util.StringUtils;
import com.twotiger.and.util.ViewUtils;

/**
 * 活期转出
 * @Description: TODO(这里描述这个类的作用) 
 * @Author douxy
 * @Date 2015年8月12日 下午2:50:58
 */
public class CurrentInputAmountOutPage extends BaseActivity implements OnClickListener {
    private static final int TOPROJECTXOUTSUCCES = 0;
    private static final int TOPROJECTXOUTFAIL = 1;
    private static final int CURRENT_PROJECTXOUTSUCCES = 2;
    private static final int CURRENT_PROJECTXOUTFAIL = 3;
    private static final int COUNTINVERSTSUCCES = 4;
    private static final int COUNTINVERSTFAIL = 5;
    private static final int LOOPTOCOUNTINSERT = 6;

    private TextView tv_canout_amount, tv_current_assert, tv_lose, tv_lose_days, tv_out_time;
    private Button btn_out;
    private EditText input_amount_edit;
    private HashMap<String, String> parm;
    private SubTitle subTitle;
    private ImageView iv_out_tishi_1, iv_out_tishi_2;

    private String amountContent; //金额输入框的内容
    private String tempNumNow;
    private ToProjectXOut mToProjectXOut;
    private TextView tv_current_out_update_tip;

    @Override
    protected View loadViewLayout(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.input_current_amount_out_layout, null);
        return view;
    }

    @Override
    protected void findViewById(View view) {

        subTitle = new SubTitle(view) {
            @Override
            protected void clickTitle(View v) {
            }

            @Override
            protected void clickRightBtn(View v) {
            }

            @Override
            protected void cickLeftBtn(View v) {
                onBackPress();
            }
        };
        subTitle.setTitle("活期转出");
        subTitle.hideBtns();
        subTitle.title_left_bt.setVisibility(View.VISIBLE);

        iv_out_tishi_1 = (ImageView) view.findViewById(R.id.iv_out_tishi_1);
        iv_out_tishi_2 = (ImageView) view.findViewById(R.id.iv_out_tishi_2);
        tv_canout_amount = (TextView) view.findViewById(R.id.tv_canout_amount);
        tv_current_assert = (TextView) view.findViewById(R.id.tv_current_assert);
        input_amount_edit = (EditText) view.findViewById(R.id.input_amount_edit);
        tv_lose = (TextView) view.findViewById(R.id.tv_lose);
        tv_lose_days = (TextView) view.findViewById(R.id.tv_lose_days);
        tv_out_time = (TextView) view.findViewById(R.id.tv_out_time);
        btn_out = (Button) view.findViewById(R.id.btn_out);
        tv_current_out_update_tip = (TextView) view.findViewById(R.id.tv_current_out_update_tip);

    }

    @Override
    public void onClick(View view) {

        if (view == null) {
            return;
        }

        switch (view.getId()) {
        case R.id.sub_title_left_bt:
            onBackPress();
            break;
        case R.id.iv_out_tishi_1:
            if(mToProjectXOut == null){
                return;
            }
            PromptManager.showCurrentAlert(CurrentInputAmountOutPage.this, "可转出余额",
                "今日可转出余额是为了满足平台用户的正常转出的同时避免平台产生流动性风险。今日可转出余额" + mToProjectXOut.getOutMsg()
                        + "。\n具体额度根据平台日常运营数据和风险管控机制的基础上得出。");
            break;
        case R.id.iv_out_tishi_2:
            PromptManager.showCurrentAlert(CurrentInputAmountOutPage.this, "预计转出时间",
                "老虎活期的每一笔投资都会分散投资到老虎直投的项目中去，平台不设资金池。\n用户转出活期资产时，由系统发起转让，等待其他用户买入。");
            break;
        case R.id.btn_out:
            if (ViewUtils.isFastDoubleClick(view)) {
                return;
            }
            String input_amount = input_amount_edit.getText().toString().trim();
            if (StringUtils.isEmpty(input_amount) || Double.parseDouble(input_amount) == 0) {
                showToast("请输入转出金额");
                return;
            }
            if (mToProjectXOut == null) {
                return;
            }
            if (Double.parseDouble(input_amount) > mToProjectXOut.getOutAmount()) {
                showToast("转出金额大于今日可转出余额");
                return;
            }
            if (Double.parseDouble(input_amount) > mToProjectXOut.getAmount()) {
                showToast("转出金额大于活期资产");
                return;
            }
            PromptManager.showCurrentAlertHasBtn(mContext, "转出确认",
                "您将转出资金至可用余额\n金额：" + ArithUtils.coverMoney(input_amount) + "元", "确认转出", true,
                new ReChargeClickListener() {

                    @Override
                    public void onClickConfirm() {
                        doCurrentOut();
                    }

                    @Override
                    public void onClickCancel() {

                    }
                });

            break;
        }
    }

    protected void doCurrentOut() {
        parm.clear();
        parm.put("token", getToken());
        parm.put("amount", ArithUtils.coverMoney(input_amount_edit.getText().toString().trim()));
        getDate(parm, Constants.PROJECTXOUT, handler, CURRENT_PROJECTXOUTSUCCES,
            CURRENT_PROJECTXOUTFAIL, true, false, false);
    }

    @Override
    protected void setListener() {

        amountContent = input_amount_edit.getText().toString().trim();

        btn_out.setOnClickListener(this);
        iv_out_tishi_1.setOnClickListener(this);
        iv_out_tishi_2.setOnClickListener(this);

        handler = new BaseHandler(this) {

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case COUNTINVERSTSUCCES:
                    Basebean result_1 = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result_1.isOk()) {
                        Interest interest = JSON.parseObject(result_1.data, Interest.class);
                        tv_lose_days.setText("转出后" + interest.getDays() + "天您将损失：");
                        tv_lose.setText(ArithUtils.formatFloatNumber(interest.getInterest()) + "");
                    } else {
                        showToast(result_1.codeDesc);
                    }
                    break;
                case COUNTINVERSTFAIL:

                    break;
                case TOPROJECTXOUTSUCCES:
                    Basebean result = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result.isOk()) {
                        mToProjectXOut = JSONObject.parseObject(result.data, ToProjectXOut.class);
                        initData();
                    } else {
                        showToast(result.codeDesc);
                    }
                    break;
                case TOPROJECTXOUTFAIL:
                    showToast("网络异常");
                    break;
                case CURRENT_PROJECTXOUTSUCCES:
                    Basebean result_2 = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result_2.isOk()) {
                        CurrentEnter mCurrentEnter = JSONObject.parseObject(result_2.data,
                            CurrentEnter.class);
                        int cc = mCurrentEnter.getCount();
                        int maxCc = mCurrentEnter.getMaxCount();
                        if (cc >= maxCc - 2) {
                            PromptManager.showCurrentAlertCommon(mContext, 0,
                                "转出成功!", "最晚一天内到可用余额~", "我知道了", "", false, true, PromptManager.SUCCESS,
                                (maxCc - cc) + "", new ReChargeClickListener() {

                                    @Override
                                    public void onClickConfirm() {
                                        finish();
                                    }

                                    @Override
                                    public void onClickCancel() {

                                    }
                                });
                        } else {
                            PromptManager.showCurrentAlertCommon(mContext, 0,
                                "转出成功!", "最晚一天内到可用余额~", "我知道了", "", false, false,
                                PromptManager.SUCCESS, "", new ReChargeClickListener() {

                                    @Override
                                    public void onClickConfirm() {
                                        finish();
                                    }

                                    @Override
                                    public void onClickCancel() {

                                    }
                                });
                        }
                    } else {
                        PromptManager.showCurrentAlertCommon(mContext, 0, "转出失败!",
                            result_2.codeDesc, "我知道了", "", false, true,
                            PromptManager.FAILURRE, "", new ReChargeClickListener() {

                                @Override
                                public void onClickConfirm() {

                                }

                                @Override
                                public void onClickCancel() {

                                }
                            });
                    }

                    break;
                case CURRENT_PROJECTXOUTFAIL:
                    showToast("网络异常");
                    break;
                case LOOPTOCOUNTINSERT: //轮询看是否需要计算收益
                    tempNumNow = amountContent;
                    String temp = (String) msg.obj;
                    if (!StringUtils.isEmpty(tempNumNow) && Double.parseDouble(tempNumNow) != 0) {
                        if (tempNumNow.equals(temp)) {
                            if (!ArithUtils.isValidAmount(tempNumNow)) {
                                showToast("请输入有效金额");
                                break;
                            }
                            countinsert(tempNumNow.toString());
                        }
                    }
                default:
                    break;
                }
                super.handleMessage(msg);
            }
        };

        input_amount_edit.addTextChangedListener(new TextWatcher() {

            String aaa = "";

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                aaa = s.toString(); //edittext变化之前的内容
            }

            @Override
            public void afterTextChanged(Editable s) {
                String bbb = s.toString();//edittext变化之后的内容
                if (".".equals(s.toString())) {
                    input_amount_edit.setText("");
                    return;
                }
                if (!bbb.equals(aaa)) {
                    if (!StringUtils.isEmpty(s.toString())) {
                        if(mToProjectXOut == null){
                            return;
                        }
                        if (Double.parseDouble(s.toString()) > mToProjectXOut.getOutAmount()) {
                            input_amount_edit.setText(aaa);
                            input_amount_edit.setSelection(aaa.length() - 1);
                            return;
                        }
                        if (Double.parseDouble(s.toString()) > mToProjectXOut.getAmount()) {
                            input_amount_edit.setText(aaa);
                            input_amount_edit.setSelection(aaa.length() - 1);
                            return;
                        }
                    }
                    if (!StringUtils.isEmpty(s.toString())) {
                        if (Double.parseDouble(s.toString()) == 0) {
                            tv_lose.setText("--");
                            amountContent = s.toString();
                        } else {
                            tv_lose.setText("计算中...");
                            amountContent = s.toString();
                        }
                    } else {
                        tv_lose.setText("--");
                        amountContent = s.toString();
                    }
                    String tempNumPre = amountContent;
                    Message preNumMes = Message.obtain();
                    preNumMes.obj = tempNumPre;
                    preNumMes.what = LOOPTOCOUNTINSERT;
                    handler.sendMessageDelayed(preNumMes, 1000); //发送一个延迟3秒的消息。系统收到消息后会对比文本框内容是否有变化。如果没有变化则请求预期收益接口

                }
            }
        });
    }

    protected void initData() {
        tv_canout_amount.setText(ArithUtils.coverMoneyComma(mToProjectXOut.getOutAmount() + ""));
        tv_current_assert
            .setText(ArithUtils.coverMoneyComma(mToProjectXOut.getAmount() + "") + "元");
        tv_out_time.setText("预计转出时间：" + mToProjectXOut.getOutDateMsg());
        tv_current_out_update_tip.setText(mToProjectXOut.getOutMsg());
    }

    @Override
    protected void processLogic() {
        //        input_amount_edit.requestFocus();
        //        //弹出键盘
        //        this.getWindow().setSoftInputMode(
        //            WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

        parm = getParm();
        toProjectXOut();

    }

    /**
     * 预期收益计算
     * 
     * @param money
     */
    private void countinsert(String money) {
        parm.clear();
        parm.put("amount", ArithUtils.coverMoney(money));
        getDate(parm, Constants.PROJECTXCALINTEREST, handler, COUNTINVERSTSUCCES,
            COUNTINVERSTFAIL, false, true, false);
    }

    private void toProjectXOut() {
        parm.clear();
        parm.put("token", getToken());
        getDate(parm, Constants.TOPROJECTXOUT, handler, TOPROJECTXOUTSUCCES,
            TOPROJECTXOUTFAIL, false, true, false);
    }

    @Override
    protected void onBackPress() {
        finish();
        overridePendingTransition(R.anim.silent_anim, R.anim.slide_out_to_bottom);
    }

}
